Replace elements with greatest element on right side

Time: O(N); Space: O(1); easy

Given an array arr, replace every element in that array with the greatest element among the elements to its right, and replace the last element with -1.

After doing so, return the array.

Example 1:

Input: arr = [17,18,5,4,6,1]

Output: [18,6,6,6,1,-1]

Notes:

  • 1 <= len(arr) <= 10^4

Hints:

  1. Loop through the array starting from the end.

  2. Keep the maximum value seen so far.

[3]:
class Solution1(object):
    def replaceElements(self, arr):
        """
        :type arr: List[int]
        :rtype: List[int]
        """
        curr_max = -1
        for i in reversed(range(len(arr))):
            arr[i], curr_max = curr_max, max(curr_max, arr[i])
        return arr
[4]:
s = Solution1()
arr = [17,18,5,4,6,1]
assert s.replaceElements(arr) == [18,6,6,6,1,-1]